﻿using Engine;
using Engine.Graphics;
using Game;
using GameEntitySystem;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using TemplatesDatabase;
using XmlUtilities;
using Random = Game.Random;

namespace SAGhoul.Tartareosity
{
	public class SubsystemWorld : Subsystem, IUpdateable
	{
		public SubsystemTerrain m_subsystemTerrain;
		public SubsystemGameInfo m_subsystemGameInfo;
		public SubsystemBodies m_subsystemBodies;
		public SubsystemTime m_subsystemTime;
		public SubsystemSpawn m_subsystemSpawn;
		public SubsystemPlayers m_subsystemPlayers;
		public SubsystemPortals m_subsystemPortals;
		public SubsystemAudio m_subsystemAudio;

		public WorldType WorldType
		{
			get;
			set;
		}

		/// <summary>
		/// 生物实体列表
		/// 传送时通过SaveCreatures方法往Creatures添加数据
		/// 然后在Load时，从Creatures中填充
		/// </summary>
		public List<Entity> m_creatureEntitys = [];

		/// <summary>
		/// 当前世界路径
		/// </summary>
		public string m_worldPath;
		/// <summary>
		/// 上一个世界路径
		/// </summary>
		public string LastWorldPath = string.Empty;

		public bool m_initialize;

		private bool m_canGenerateDoor;
		private bool m_playPortalAudio;

		private float m_lastDtime = 0f;

		public Random m_random = new();

		public UpdateOrder UpdateOrder => UpdateOrder.Default;

		/// <summary>
		/// 切换世界时执行事件
		/// </summary>
		public event Action ChangeWorldEvent;

		/// <summary>
		/// 加载传送动物前执行事件
		/// </summary>
		public event Action<Entity> LoadCreatureEntityBegin;

		/// <summary>
		/// 加载传送动物后执行事件
		/// </summary>
		public event Action<Entity> LoadCreatureEntityEnd;

		/// <summary>
		/// 禁止传送
		/// 每次进入存档都会禁止传送10s
		/// </summary>
		public bool ProhibitTransmission = true;

		public void TransPortal()
		{
			if (WorldType == WorldType.Default)
				MajorToChildWorld();
			else
				ChildToMajorWorld();
		}
		public override void Load(ValuesDictionary valuesDictionary)
		{
			m_subsystemPlayers = Project.FindSubsystem<SubsystemPlayers>();
			m_subsystemTime = Project.FindSubsystem<SubsystemTime>();
			m_subsystemGameInfo = Project.FindSubsystem<SubsystemGameInfo>();
			m_subsystemTerrain = base.Project.FindSubsystem<SubsystemTerrain>();
			m_subsystemBodies = base.Project.FindSubsystem<SubsystemBodies>();
			m_subsystemSpawn = base.Project.FindSubsystem<SubsystemSpawn>();
			m_subsystemPortals = base.Project.FindSubsystem<SubsystemPortals>();
			m_subsystemAudio = base.Project.FindSubsystem<SubsystemAudio>();

			var gameLoadingScreen = ScreensManager.FindScreen<GameLoadingScreen>("GameLoading");

			m_worldPath = valuesDictionary.GetValue<string>("WorldPath", gameLoadingScreen.m_worldInfo.DirectoryName);
			LastWorldPath = valuesDictionary.GetValue<string>("LastWorldPath", m_worldPath);
			m_playPortalAudio = valuesDictionary.GetValue<bool>("PlayPortalAudio", false);

			WorldType = GetWorldType(m_worldPath);
			m_subsystemTime.QueueGameTimeDelayedExecution(m_subsystemTime.GameTime + 10f, delegate
			{
				ProhibitTransmission = false;
			});

			m_canGenerateDoor = false;
			m_initialize = false;

			LoadAndSpawnCreatures(valuesDictionary);
			base.Load(valuesDictionary);
		}
		public override void Save(ValuesDictionary valuesDictionary)
		{
			//保存当前与上次世界的存档路径
			valuesDictionary.SetValue<string>("WorldPath", m_worldPath);
			valuesDictionary.SetValue<string>("LastWorldPath", LastWorldPath);
			valuesDictionary.SetValue<bool>("PlayPortalAudio", m_playPortalAudio);
			base.Save(valuesDictionary);
		}

		//实体添加方法，每当实体被添加时执行一次
		public override void OnEntityAdded(Entity entity)
		{
			var componentPlayer = entity.FindComponent<ComponentPlayer>();
			if (componentPlayer != null)
			{
				if (componentPlayer.PlayerData.SpawnPosition == Vector3.Zero)
				{
					m_canGenerateDoor = true;
					var coarsePosition = m_subsystemTerrain.TerrainContentsGenerator.FindCoarseSpawnPosition();
					componentPlayer.PlayerData.SpawnPosition = coarsePosition;
					componentPlayer.ComponentBody.Position = coarsePosition;
				}
			}
			base.OnEntityAdded(entity);
		}

		//实体移除方法，每当实体被移除时执行一次
		public override void OnEntityRemoved(Entity entity)
		{
			base.OnEntityRemoved(entity);
		}

		//释放方法，关闭存档时执行一次
		public override void Dispose()
		{
			base.Dispose();
		}

		public void Update(float dt)
		{
			if (m_subsystemPlayers == null || m_subsystemPlayers.ComponentPlayers.Count <= 0)
				return;

			m_lastDtime += dt;
			//新世界构建传送门
			if (m_canGenerateDoor)
			{
				if (m_lastDtime > 1f)
				{
					GenerateDoor(new Point3(m_subsystemPlayers.ComponentPlayers[0].ComponentBody.Position) + new Point3(0, 1, 2));
					m_canGenerateDoor = false;
				}
			}
			var firstPlayerPosition = new Point3(m_subsystemPlayers.ComponentPlayers[0].ComponentBody.Position);
			if (m_playPortalAudio)
			{
				if (m_lastDtime > 1f)
				{
					m_subsystemAudio.PlaySound("Audio/Tartareosity/Portal_Arrive", 1.1f, m_random.Float(-0.3f, 0.3f), firstPlayerPosition, 3f, autoDelay: false);
					m_playPortalAudio = false;
				}
			}

			if (!m_initialize)
			{
				m_initialize = true;


				#region 加载传送动物前执行
				foreach (var creatureEntity in m_creatureEntitys)
				{
					LoadCreatureEntityBegin?.Invoke(creatureEntity);
					var v = new Point3(0, 0, 0);
					int num = 0;
					while (num <= 5)
					{
						int x = firstPlayerPosition.X + m_random.Int(-5, 5);
						int y = firstPlayerPosition.Y + num;
						int z = firstPlayerPosition.Z + m_random.Int(-5, 5);
						int i = m_subsystemTerrain.Terrain.GetCellContents(x, y, z);
						if (i == 0)
						{
							v = new Point3(x, y, z);
							break;
						}
						else
						{
							num++;
						}
					}
					var body = creatureEntity.FindComponent<ComponentBody>();

					body.Position = new Vector3(v.X, v.Y, v.Z);

					body.Rotation = Quaternion.CreateFromAxisAngle(Vector3.UnitY, m_random.Float(0f, (float)MathUtils.PI * 2f));
					creatureEntity.FindComponent<ComponentSpawn>().SpawnDuration = 0f;
					Project.AddEntity(creatureEntity);
				}
				#endregion

				#region 加载传送动物后执行
				foreach (var creatureEntity in m_creatureEntitys)
				{
					LoadCreatureEntityEnd?.Invoke(creatureEntity);
				}
				#endregion

				m_creatureEntitys.Clear();//清理
			}

			//捕捉实体位置（是否进入传送门）
			foreach (var portal in m_subsystemPortals.Portals)
			{
				var v1 = portal.Min;
				var v2 = portal.Max;
				//玩家拟进入传送门
				foreach (var player in m_subsystemPlayers.ComponentPlayers)
				{
					var p = player.ComponentBody.Position;
					if (p.X >= v1.X && p.Y >= v1.Y && p.Z >= v1.Z && p.X <= v2.X && p.Y <= v2.Y && p.Z <= v2.Z)
					{
						TransPortal();
						break;
					}
				}

				//动物拟进入传送门
				var dynamicArray = new DynamicArray<ComponentBody>();
				m_subsystemBodies.FindBodiesInArea(v1.XZ - new Vector2(8f), v2.XY + new Vector2(8f), dynamicArray);
				foreach (var creatureBody in dynamicArray)
				{
					var p2 = creatureBody.Position;
					if (p2.X >= v1.X && p2.Y >= v1.Y && p2.Z >= v1.Z && p2.X <= v2.X && p2.Y <= v2.Y && p2.Z <= v2.Z)
					{
						var player = creatureBody.Entity.FindComponent<ComponentPlayer>();
						if (player == null)
						{
							base.Project.RemoveEntity(creatureBody.Entity, true);
							var entites = new List<Entity> { creatureBody.Entity };
							if (WorldType == WorldType.Default)
							{
								MajorToChildWorld(isAnimal: true, entites);
							}
							else
							{
								ChildToMajorWorld(isAnimal: true, entites);
							}

						}
					}
				}
			}
		}
		#region 传送逻辑相关

		/// <summary>
		/// 计算路径
		/// </summary>
		private string CalculateTargetPath(string currentPath, bool isCurrentChild, string targetWorldName, WorldTransferType transferType)
		{
			switch (transferType)
			{
				case WorldTransferType.ToLastWorld:
					if (!string.IsNullOrEmpty(LastWorldPath))//上一个世界路径
					{
						var lastPathRoot = IsChildWorld(LastWorldPath)
							? Storage.GetDirectoryName(LastWorldPath)
							: LastWorldPath;
						var currentRoot = isCurrentChild
							? Storage.GetDirectoryName(currentPath)
							: currentPath;
						return lastPathRoot == currentRoot ? LastWorldPath : null;
					}
					return isCurrentChild ? Storage.GetDirectoryName(currentPath) : null;

				case WorldTransferType.ChildToMajor:
					return Storage.GetDirectoryName(currentPath);

				case WorldTransferType.MajorToChild:
					return Storage.CombinePaths(currentPath, targetWorldName);

				case WorldTransferType.ChildToChild:
					return Storage.CombinePaths(Storage.GetDirectoryName(currentPath), targetWorldName);

				default:
					return null;
			}
		}

		/// <summary>
		/// 验证是否可以传送
		/// </summary>
		private bool ValidateTransfer(string currentPath, string targetPath, bool isCurrentChild, WorldTransferType transferType)
		{
			//			// 通用验证
			//			if (ProhibitTransmission)
			//			{
			//				base.Project.FindSubsystem<SubsystemSpaceRingBlockBehavior>().m_transferring = false;
			//#if !DEBUG
			//				ShowMessage("刚进入世界10秒内禁止传送，请等待片刻", Color.Red);
			//				return false;
			//#endif
			//			}

			// 特定验证 
			switch (transferType)
			{
				case WorldTransferType.ChildToMajor when !isCurrentChild:
					Log.Warning("Current world is not child world");
					return false;

				case WorldTransferType.MajorToChild:
					if (isCurrentChild)
					{
						Log.Warning("Current world is not major world");
						return false;
					}
					if (!IsChildWorld(targetPath))
					{
						Log.Warning("Target world is not child world");
						return false;
					}
					break;

				case WorldTransferType.ChildToChild:
					if (!isCurrentChild)
					{
						Log.Warning("Current world is not child world");
						return false;
					}
					if (!IsChildWorld(targetPath))
					{
						Log.Warning("Target world is not child world");
						return false;
					}
					break;
			}
			return true;
		}

		/// <summary>
		/// 传送前特殊处理
		/// </summary>
		private bool PreTransferProcessing(string targetPath)
		{
			//// 元神状态检查 
			//var player = m_subsystemPlayers.ComponentPlayers.FirstOrDefault();
			//var isSoulEscaping = player?.Entity.FindComponent<BuffComponent>()?
			//				   .FindBuff<SoulEscapeBuff>("出窍")?.IsReleasing ?? false;
			//if (isSoulEscaping)
			//{
			//	ShowMessage("元神无法进行传送", Color.Red);
			//	return false;
			//}

			//获取目标世界类型
			var worldType = GetWorldType(targetPath);
			var timeStr = GetAttributeValue(targetPath, new[] { "Subsystems", "GameInfo", "TotalElapsedGameTime" });
			var elapsedTime = string.IsNullOrEmpty(timeStr) ? 0f : float.Parse(timeStr);

			//if (elapsedTime / 1200f > 3f) // 3天游戏时间
			//{
			//	var relevantWorldTypes = new HashSet<WorldType>
			//	{
			//		WorldType.暗幽牢狱,
			//		WorldType.冰域,
			//		WorldType.闪雷界,
			//		WorldType.血色禁地,
			//		WorldType.域外战场,
			//		WorldType.元空秘境,
			//		WorldType.梦魇战场
			//	};
			//	var isRelevantWorld = relevantWorldTypes.Contains(worldType);
			//	if (isRelevantWorld)
			//	{
			//		WorldsManager.DeleteWorld(targetPath);
			//		Log.Warning($"{worldType.ToString()} 已重置");
			//	}
			//}
			return true;
		}

		/// <summary>
		/// 执行世界传送
		/// </summary>
		/// <param name="currentPath">当前路径</param>
		/// <param name="targetPath">目标路径</param>
		/// <param name="entites">实体列表</param>
		private void ExecuteWorldTransfer(string currentPath, string targetPath, List<Entity> entites)
		{
			if (entites != null)
			{
				var result = new Dictionary<int, SpawnEntityData>();  // 改用字典 
				foreach (var entity in entites)
				{
					var data = new SpawnEntityData
					{
						TemplateName = entity.ValuesDictionary.DatabaseObject.Name,
						Data = string.Empty,
						EntityId = entity.Id
					};

					var componentSpawn = entity.FindComponent<ComponentSpawn>();
					ModsManager.HookAction("OnSaveSpawnData", loader =>
					{
						loader.OnSaveSpawnData(componentSpawn, data);
						return true;
					});

					result[entity.Id] = data;
#if DEBUG
                    var worldName = Path.GetFileName(targetPath);
                    var perfectComponent = entity.FindComponent<PerfectEntityComponent>();
                    Log.Warning($"将{perfectComponent.DataManager.DisplayName}(ID:{entity.Id})传送至{worldName}");
#endif
				}
				SaveEntityDatas(targetPath, result.Values.ToList());
			}
			else
			{
				ChangeWorld(currentPath, targetPath);
			}
		}

		#endregion

		#region 传送方法

		/// <summary>
		/// 核心传送方法
		/// </summary>
		/// <param name="targetWorldName">目标世界</param>
		/// <param name="transferType">传送类型</param>
		/// <param name="entites">传送实体列表</param>
		/// <returns></returns>
		public bool InternalTransfer(string targetWorldName, WorldTransferType transferType, List<Entity> entites)
		{
			try
			{
				if (GameManager.WorldInfo == null)
					return false;

				// 获取当前路径和世界类型
				var currentPath = m_worldPath;
				var isCurrentChild = IsChildWorld(currentPath);

				// 计算目标路径 
				var targetPath = CalculateTargetPath(currentPath, isCurrentChild, targetWorldName, transferType);
				if (targetPath == null)
					return false;

				// 验证传送条件
				if (!ValidateTransfer(currentPath, targetPath, isCurrentChild, transferType))
					return false;

				// 传送前特殊处理
				if (!PreTransferProcessing(targetPath))
					return false;

				// 执行实际传送 
				ExecuteWorldTransfer(currentPath, targetPath, entites);

				return true;
			}
			catch (Exception e)
			{
				Log.Error($"Error trans world: ({transferType}): {e.Message}");
				return false;
			}
		}

		/// <summary>
		/// 返回上一个世界
		/// </summary>
		public void ToLastWorld(List<Entity> entites = null)
		{
			InternalTransfer(null, WorldTransferType.ToLastWorld, entites);
		}
		/// <summary>
		/// 子世界传送到主世界
		/// </summary>
		public void ChildToMajorWorld(bool isAnimal = false, List<Entity> entites = null)
		{
			InternalTransfer(null, WorldTransferType.ChildToMajor, isAnimal ? entites : null);
		}
		/// <summary>
		/// 主世界传送到子世界
		/// </summary>
		public void MajorToChildWorld(bool isAnimal = false, List<Entity> entites = null)
		{
			InternalTransfer(((WorldType)1).ToString(), WorldTransferType.MajorToChild, isAnimal ? entites : null);
		}
		/// <summary>
		/// 子世界传送到子世界
		/// </summary>
		public void ChildToChildWorld(string worldName, bool isAnimal = false, List<Entity> entites = null)
		{
			InternalTransfer(worldName, WorldTransferType.ChildToChild, isAnimal ? entites : null);
		}
		#endregion

		#region 传送对象

		#region 实体传送相关

		/// <summary>
		/// 保存被传送的实体数据集合到对应世界
		/// </summary>  
		public void SaveEntityDatas(string path, List<SpawnEntityData> spawnsDatas)
		{
			try
			{
				// 将全部的SpawnEntityData转化为string
				var creatureDatas = m_subsystemSpawn.SaveSpawnsData(spawnsDatas);
				if (string.IsNullOrEmpty(creatureDatas))
					return;

				XElement xElement = null;
				var isNewWorld = false;
				if (!Storage.DirectoryExists(path))
				{
					// 创建新的子世界存档
					isNewWorld = true;
					Storage.CreateDirectory(path);
					CreateNewWorld(path);
				}
				using (Stream stream = Storage.OpenFile(Storage.CombinePaths(path, "Project.xml"), OpenFileMode.Read))
				{
					xElement = XmlUtils.LoadXmlFromStream(stream, null, throwOnError: true);
				}
				if (isNewWorld)
				{
					var subWorldXElement = new XElement("Values");
					XmlUtils.SetAttributeValue(subWorldXElement, "Name", "Tartareosity");
					var creatureXElement = new XElement("Value");
					XmlUtils.SetAttributeValue(creatureXElement, "Name", "CreatureDatas");
					XmlUtils.SetAttributeValue(creatureXElement, "Type", "string");
					XmlUtils.SetAttributeValue(creatureXElement, "Value", creatureDatas);
					subWorldXElement.Add(creatureXElement);
					xElement.Element("Subsystems").Add(subWorldXElement);
				}
				else
				{
					foreach (XElement element in xElement.Element("Subsystems").Elements())
					{
						if (XmlUtils.GetAttributeValue<string>(element, "Name") == "Tartareosity")
						{
							bool existCreatures = false;
							foreach (XElement e in element.Elements())
							{
								if (XmlUtils.GetAttributeValue<string>(e, "Name") == "CreatureDatas")
								{
									existCreatures = true;
									string existingCreatureDatas = XmlUtils.GetAttributeValue<string>(e, "Value");
									if (existingCreatureDatas == "Null")
									{
										existingCreatureDatas = "";
									}
									else
									{
										if (!existingCreatureDatas.EndsWith(";"))
											existingCreatureDatas += ";";
									}
									XmlUtils.SetAttributeValue(e, "Value", existingCreatureDatas + creatureDatas);
									break;
								}
							}
							if (!existCreatures)
							{
								var creatureXElement = new XElement("Value");
								XmlUtils.SetAttributeValue(creatureXElement, "Name", "CreatureDatas");
								XmlUtils.SetAttributeValue(creatureXElement, "Type", "string");
								XmlUtils.SetAttributeValue(creatureXElement, "Value", creatureDatas);
								element.Add(creatureXElement);
							}
							break;
						}
					}
				}
				using Stream stream2 = Storage.OpenFile(Storage.CombinePaths(path, "Project.xml"), OpenFileMode.Create);
				XmlUtils.SaveXmlToStream(xElement, stream2, null, throwOnError: true);
			}
			catch (Exception e)
			{
				Log.Warning("SubsystemWorld.SaveCreatures:" + e.Message);
			}
		}

		/// <summary>
		/// 加载和生成实体
		/// </summary>
		public void LoadAndSpawnCreatures(ValuesDictionary valuesDictionary)
		{
			// 获取从其他世界传送来的动物集合
			if (valuesDictionary.ContainsKey("CreatureDatas"))
			{
				var creatures = valuesDictionary.GetValue<string>("CreatureDatas");
				if (creatures != "Null")
				{
					var spawnEntityDatas = LoadSpawnsData(creatures);
					foreach (var data in spawnEntityDatas)
					{
						var entity = SpawnEntity(data);
						if (entity != null)
						{
							m_creatureEntitys.Add(entity);
						}
					}
				}
				// 将 CreatureDatas 设置为 "Null"，表示已经处理过
				valuesDictionary.SetValue<string>("CreatureDatas", "Null");
			}
		}

		/// <summary>
		/// 只添加实体，但是不生成
		/// </summary>
		public Entity SpawnEntity(SpawnEntityData data)
		{
			try
			{
				var valuesDictionary = DatabaseManager.FindEntityValuesDictionary(data.TemplateName, true);
				var entity = Project.CreateEntity(valuesDictionary, data.EntityId);
				ModsManager.HookAction("OnReadSpawnData", (ModLoader loader) => { loader.OnReadSpawnData(entity, data); return true; });
				entity.FindComponent<ComponentBody>(throwOnError: true).Position = data.Position;
				entity.FindComponent<ComponentBody>(throwOnError: true).Rotation = Quaternion.CreateFromAxisAngle(Vector3.UnitY, m_random.Float(0f, (float)Math.PI * 2f));
				var componentCreature = entity.FindComponent<ComponentCreature>();
				componentCreature?.ConstantSpawn = data.ConstantSpawn;
				return entity;
			}
			catch (Exception ex)
			{
				Log.Error($"Can't spawn entity by template \"{data.TemplateName}\". Reason: {ex}");
				return null;
			}
		}

		/// <summary>
		/// 加载生物数据
		/// </summary>
		public List<SpawnEntityData> LoadSpawnsData(string data)
		{
			var result = new List<SpawnEntityData>();
			if (string.IsNullOrEmpty(data) || data == "Null")
			{
				return result;
			}

			var entries = data.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (var entry in entries)
			{
				if (string.IsNullOrEmpty(entry))
					continue;

				var parts = entry.Split(new char[] { ',' });
				if (parts.Length < 7)
					continue; // 确保每个条目至少有7个字段

				var spawnEntityData = new SpawnEntityData
				{
					TemplateName = parts[0],
					Position = new Vector3
					{
						X = float.Parse(parts[1], CultureInfo.InvariantCulture),
						Y = float.Parse(parts[2], CultureInfo.InvariantCulture),
						Z = float.Parse(parts[3], CultureInfo.InvariantCulture)
					},
					ConstantSpawn = bool.Parse(parts[4])
				};

				if (parts.Length >= 6)
				{
					spawnEntityData.Data = parts[5];
				}
				else
				{
					spawnEntityData.Data = string.Empty;
				}

				if (parts.Length >= 7)
				{
					spawnEntityData.EntityId = int.Parse(parts[6]);
				}
				else
				{
					spawnEntityData.EntityId = 0; // 提供默认值
				}

				result.Add(spawnEntityData);
			}
			return result;
		}

		#endregion

		/// <summary>
		/// 切换世界(玩家传送直接切换世界)
		/// </summary>     
		/// <param name="currentPath">当前路径</param>
		/// <param name="targetPath">目标路径</param>
		public void ChangeWorld(string currentPath, string targetPath)
		{
			ChangeWorldEvent?.Invoke();
			var isNewSubWorld = false;
			//目录中没有该路径
			if (!Storage.DirectoryExists(targetPath))
			{
				//创建新的子世界存档
				Storage.CreateDirectory(targetPath);
				isNewSubWorld = true;
				CreateNewWorld(targetPath);
			}

			//获取子世界的Info对象，关闭当前存档
			var subworldInfo = WorldsManager.GetWorldInfo(targetPath);
			GameManager.SaveProject(true, true);
			try
			{
				//获取当前存档XElement对象
				XElement rxElement = null;
				//获取目标存档的XElement对象
				XElement subXElement = null;
				using (Stream stream = Storage.OpenFile(Storage.CombinePaths(currentPath, "Project.xml"), OpenFileMode.Read))
				{
					rxElement = XmlUtils.LoadXmlFromStream(stream, null, throwOnError: true);//当前存档
				}
				using (Stream stream = Storage.OpenFile(Storage.CombinePaths(targetPath, "Project.xml"), OpenFileMode.Read))
				{
					subXElement = XmlUtils.LoadXmlFromStream(stream, null, throwOnError: true);//目标存档
				}

				#region 这个阶段仅仅能替换PlayerStats
				XElement playerStatsElement = null;
				XElement memoryBankBlockBehaviorElement = null;
				XElement blocksManagerElement = null;
				XElement truthTableCircuitBlockBehaviorElement = null;
				XElement extraDataElement = null;
				//获取当前存档的数据
				foreach (XElement element in rxElement.Element("Subsystems").Elements())
				{
					var elementName = XmlUtils.GetAttributeValue<string>(element, "Name");
					if (elementName == "PlayerStats")
						playerStatsElement = element;//获取当前存档的PlayerStats
					else if (elementName == "MemoryBankBlockBehavior")
						memoryBankBlockBehaviorElement = element;
					else if (elementName == "BlocksManager")
						blocksManagerElement = element;
					else if (elementName == "TruthTableCircuitBlockBehavior")
						truthTableCircuitBlockBehaviorElement = element;
					else if (elementName == "PolyGunInstances")
						extraDataElement = element;
				}
				//获取目标存档的数据，并替换
				var subsystemsElement = subXElement.Element("Subsystems");
				foreach (var element in subsystemsElement.Elements())
				{
					var elementName = XmlUtils.GetAttributeValue<string>(element, "Name");
					if (elementName == "PlayerStats")
					{
						if (!element.Element("Values").Elements("Values").Any())
						{
							isNewSubWorld = true;//是否属于新的世界,判断玩家是否是第一次进入该世界
						}
						ReplaceNodesComplete(playerStatsElement, element);//替换PlayerStats数据
					}
					//else if (elementName == "BlocksManager")
					//	ReplaceNodesComplete(blocksManagerElement, element);
					//else if (elementName == "MemoryBankBlockBehavior")
					//	ReplaceNodesComplete(memoryBankBlockBehaviorElement, element);
					//else if (elementName == "TruthTableCircuitBlockBehavior")
					//	ReplaceNodesComplete(truthTableCircuitBlockBehaviorElement, element);
					//else if (elementName == "PolyGunInstances")
					//	ReplaceNodesComplete(extraDataElement, element);
				}
				if(blocksManagerElement != null)
					AddElement(subsystemsElement, "BlocksManager", blocksManagerElement, overwriteIfExists: true);
				if(memoryBankBlockBehaviorElement != null)
					AddElement(subsystemsElement, "MemoryBankBlockBehavior", memoryBankBlockBehaviorElement, overwriteIfExists: true);
				if(truthTableCircuitBlockBehaviorElement != null)
					AddElement(subsystemsElement, "TruthTableCircuitBlockBehavior", truthTableCircuitBlockBehaviorElement, overwriteIfExists: true);
				if(extraDataElement != null)
					AddElement(subsystemsElement, "PolyGunInstances", extraDataElement, overwriteIfExists: true);

				#endregion

				if (isNewSubWorld)//第一次传送时，创建的世界
				{
					//同步玩家信息
					if (!TryReplaceNodes(rxElement, subXElement, Name: "Players"))
					{
						Log.Error($"Failed to replace Players node");
					}

					subXElement.Descendants("Value")
						.Where(v => v.Attribute("Name")?.Value == "SpawnPosition")
						.ToList()
						.ForEach(x =>
						{
							XmlUtils.SetAttributeValue(x, "Value", Point3.Zero);
						});


					//获取玩家数据
					subXElement.Add(new XElement("Entities"));
					//从当前存档的实体节点获取
					foreach (var element in rxElement.Element("Entities").Elements())
					{
						if (XmlUtils.GetAttributeValue<string>(element, "Name") == "MalePlayer" || XmlUtils.GetAttributeValue<string>(element, "Name") == "FemalePlayer")
						{
							subXElement.Element("Entities").Add(element);
						}
					}
					#region 同步其他
					//同步设定数据
					subsystemsElement.Add(extraDataElement);
					#endregion
				}
				else // 非首次进入世界的处理
				{
					// ===== 1. 同步玩家基础数据 =====
					var sourcePlayers = GetXmlNode(rxElement, "Subsystems", ("Name", "Players"));
					var targetPlayers = GetXmlNode(subXElement, "Subsystems", ("Name", "Players"));

					if (sourcePlayers?.Element("Values") is XElement srcValues &&
						targetPlayers?.Element("Values") is XElement tgtValues)
					{
						ReplaceNodes(
							newData: tgtValues,
							sourceElement: srcValues,
							reserveParameters: ["SpawnPosition"]
						);
					}

					//// ===== 2. 精确查找玩家实体 =====
					//// 源存档玩家
					//var playerEntityElement = rxElement.Element("Entities")?
					//	.Elements("Entity")
					//	.FirstOrDefault(e =>
					//	{
					//		var name = e.Attribute("Name")?.Value;
					//		return name == "MalePlayer" || name == "FemalePlayer";
					//	});
					//// 目标存档玩家 
					//var targetPlayerEntity = subXElement.Element("Entities")?
					//	.Elements("Entity")
					//	.FirstOrDefault(e =>
					//	{
					//		var name = e.Attribute("Name")?.Value;
					//		return name == "MalePlayer" || name == "FemalePlayer";
					//	});
					//if (playerEntityElement != null && targetPlayerEntity != null)
					//{
					//	ReplaceNodes(
					//		newData: targetPlayerEntity,
					//		sourceElement: playerEntityElement,
					//		reserveParameters: ["Body"]
					//	);
					//}
					Dictionary<int, XElement> targetPlayersEle = [];
					foreach (var element in subXElement.Element("Entities")?.Elements())
					{//从目标存档实体中找出所有玩家数据
						var name = element.Attribute("Name")?.Value;
						if ((name == "MalePlayer" || name == "FemalePlayer") && int.TryParse(element.Attribute("Id")?.Value, out int id))
						{
							targetPlayersEle[id] = element;
						}
					}
					foreach (var playerEntityElement in rxElement.Element("Entities")?.Elements())
					{//遍历源存档实体找出玩家并与目标存档玩家数据进行匹配替换
						var name = playerEntityElement.Attribute("Name")?.Value;
						if ((name == "MalePlayer" || name == "FemalePlayer") && int.TryParse(playerEntityElement.Attribute("Id")?.Value, out int id1))
						{
							if (targetPlayersEle.TryGetValue(id1, out XElement targetPlayerEntity))
							{
								ReplaceNodesRecursive(targetPlayerEntity, playerEntityElement, reserveParameters: ["Body"]);
							}
						}
					}

					//else
					//{
					//	var errorMsg = $"玩家实体同步失败: ";
					//	errorMsg += playerEntityElement == null ? "源玩家实体未找到 " : "";
					//	errorMsg += targetPlayerEntity == null ? "目标玩家实体未找到" : "";
					//	Log.Error(errorMsg.Trim());
					//}
				}

				//保存同步后的目标存档
				using (Stream stream2 = Storage.OpenFile(Storage.CombinePaths(targetPath, "Project.xml"), OpenFileMode.Create))
				{
					XmlUtils.SaveXmlToStream(subXElement, stream2, null, throwOnError: true);
				}

				////同步存档基本数据
				//SynchronizeGameInfo(rxElement, subXElement, currentPath, targetPath, isNewSubWorld);

				if (targetPath != currentPath)
				{
					// 第一步：更新目标世界的LastWorldPath
					SetAttributeToTargetWorld(targetPath, currentPath, "LastWorldPath");

					// 第二步：更新目标世界的WorldPath 
					SetAttributeToTargetWorld(targetPath, targetPath, "WorldPath");

					// 第三步：内存状态同步
					LastWorldPath = currentPath;
					m_worldPath = targetPath;
					SetAttributeToTargetWorld(targetPath, true, "PlayPortalAudio", type: "bool");
				}
			}
			catch (Exception e)
			{
				Log.Error($"Failed to create Subworld(No Sych)：{e.Message}");
			}
			finally
			{
				//加载目标存档
				ScreensManager.SwitchScreen("GameLoading", subworldInfo, null);
			}
		}

		#endregion

		#region 其他辅助方法
		/// <summary>
		/// 尝试替换节点
		/// </summary>
		public static bool TryReplaceNodes(XElement targetRoot, XElement sourceRoot, string XName = "Subsystems", string Name = "")
		{
			var target = targetRoot.Elements(XName)
						  .Elements()
						  .FirstOrDefault(e => e.Attribute("Name")?.Value == Name);

			var source = sourceRoot.Elements(XName)
						  .Elements()
						  .FirstOrDefault(e => e.Attribute("Name")?.Value == Name);

			if (target == null || source == null)
				return false;

			ReplaceNodes(target, source, null);
			return true;
		}
		/// <summary>
		/// 安全获取XML节点（支持XPath/节点名/索引/属性查找）
		/// </summary>
		/// <param name="root">根节点</param>
		/// <param name="path">查找路径（支持多种定位方式）</param>
		/// <returns>找到的节点或null</returns>
		public static XElement GetXmlNode(XElement root, params object[] path)
		{
			if (root == null)
				return null;

			XElement current = root;

			foreach (var segment in path)
			{
				if (current == null)
					return null;

				try
				{
					switch (segment)
					{
						case string name when name.Contains('/'):
							// XPath模式 
							current = current.XPathSelectElement(name);
							break;

						case string name:
							// 先尝试直接按元素名查找
							current = current.Element(name);
							if (current != null)
								break;

							// 再尝试按Name属性查找（安全方式）
							current = current.Elements()
								.FirstOrDefault(e =>
									e.Attribute("Name")?.Value == name);
							break;

						case int index:
							// 索引访问（带边界检查）
							current = current.Elements().ElementAtOrDefault(index);
							break;

						case (string attrName, string attrValue):
							// 元组形式指定属性和值 (如：("Type", "Player"))
							current = current.Elements()
								.FirstOrDefault(e =>
									e.Attribute(attrName)?.Value == attrValue);
							break;

						default:
							return null;
					}
				}
				catch
				{
					return null; // 任何解析错误都返回null
				}
			}

			return current;
		}
		/// <summary>
		/// 判断是否为子世界
		/// </summary>
		public static bool IsChildWorld(string cpath)
		{
			var path = Storage.GetDirectoryName(cpath);
			return (path != WorldsManager.WorldsDirectoryName && Storage.GetDirectoryName(path) == WorldsManager.WorldsDirectoryName);
		}

		/// <summary>
		/// 创建新世界
		/// </summary>      
		public static void CreateNewWorld(string wpath)
		{
			try
			{
				var worldSettings = GameManager.WorldInfo.WorldSettings;
				int num = (int)(long)(Time.RealTime * 1000.0);
				/*
                if (string.IsNullOrEmpty(worldSettings.Seed))
                {
                    num = (int)(long)(Time.RealTime * 1000.0);
                }
                else if (worldSettings.Seed == "0")
                {
                    num = 0;
                }
                else
                {
                    num = 0;
                    int num2 = 1;
                    string seed = worldSettings.Seed;
                    foreach (char c in seed)
                    {
                        num += c * num2;
                        num2 += 29;
                    }
                }
                */
				var valuesDictionary = new ValuesDictionary();
				worldSettings.Save(valuesDictionary, liveModifiableParametersOnly: false);
				valuesDictionary.SetValue("WorldDirectoryName", wpath);
				valuesDictionary.SetValue("WorldSeed", num);
				var valuesDictionary2 = new ValuesDictionary();
				valuesDictionary2.SetValue("Players", new ValuesDictionary());
				var databaseObject = DatabaseManager.GameDatabase.Database.FindDatabaseObject("GameProject", DatabaseManager.GameDatabase.ProjectTemplateType, throwIfNotFound: true);
				var xElement = new XElement("Project");
				XmlUtils.SetAttributeValue(xElement, "Guid", databaseObject.Guid);
				XmlUtils.SetAttributeValue(xElement, "Name", "GameProject");
				XmlUtils.SetAttributeValue(xElement, "Version", VersionsManager.SerializationVersion);
				var xElement2 = new XElement("Subsystems");
				xElement.Add(xElement2);
				var xElement3 = new XElement("Values");
				XmlUtils.SetAttributeValue(xElement3, "Name", "GameInfo");
				valuesDictionary.Save(xElement3);
				xElement2.Add(xElement3);
				var xElement4 = new XElement("Values");
				XmlUtils.SetAttributeValue(xElement4, "Name", "Players");
				valuesDictionary2.Save(xElement4);
				xElement2.Add(xElement4);
				var xElement5 = new XElement("Values");
				XmlUtils.SetAttributeValue(xElement5, "Name", "PlayerStats");
				valuesDictionary2.Save(xElement5);
				xElement2.Add(xElement5);
				using Stream stream = Storage.OpenFile(Storage.CombinePaths(wpath, "Project.xml"), OpenFileMode.Create);
				XmlUtils.SaveXmlToStream(xElement, stream, null, throwOnError: true);
			}
			catch (Exception e)
			{
				Log.Warning("SubsystemWorld.CreateNewWorld:" + e.Message);
			}
		}
		/// <summary>
		/// 获取待前往世界的指定属性字符串值（获取存档中指定属性）
		/// </summary>
		/// <param name="path">路径</param>
		/// <param name="attributes">属性值</param>
		/// <returns></returns>
		public static string GetAttributeValue(string path, string[] attributes)
		{
			if (!Storage.DirectoryExists(path))//判断目录是否存在
			{
				return string.Empty;
			}
			XElement xElement = null;
			try
			{
				using (Stream stream = Storage.OpenFile(Storage.CombinePaths(path, "Project.xml"), OpenFileMode.Read))
				{
					xElement = XmlUtils.LoadXmlFromStream(stream, null, throwOnError: true);
				}
				if (xElement.Element(attributes[0]) == null)
				{
					return string.Empty;
				}
				if (attributes.Length == 3)
				{
					foreach (XElement element in xElement.Element(attributes[0]).Elements())
					{
						if (XmlUtils.GetAttributeValue<string>(element, "Name") == attributes[1])
						{
							foreach (XElement element2 in element.Elements())
							{
								if (XmlUtils.GetAttributeValue<string>(element2, "Name") == attributes[2])
								{
									return XmlUtils.GetAttributeValue<string>(element2, "Value");
								}
							}
							break;
						}
					}
				}
				else if (attributes.Length == 4)
				{
					foreach (XElement element in xElement.Element(attributes[0]).Elements())
					{
						if (XmlUtils.GetAttributeValue<string>(element, "Name") == attributes[1])
						{
							foreach (XElement element2 in element.Elements())
							{
								if (XmlUtils.GetAttributeValue<string>(element2, "Name") == attributes[2])
								{
									foreach (XElement element3 in element2.Elements())
									{
										if (XmlUtils.GetAttributeValue<string>(element3, "Name") == attributes[3])
										{
											return XmlUtils.GetAttributeValue<string>(element3, "Value");
										}
									}
									break;
								}
							}
							break;
						}
					}
				}
				else if (attributes.Length == 5)
				{
					foreach (XElement element in xElement.Element(attributes[0]).Elements())
					{
						if (XmlUtils.GetAttributeValue<string>(element, "Name") == attributes[1])
						{
							foreach (XElement element2 in element.Elements())
							{
								if (XmlUtils.GetAttributeValue<string>(element2, "Name") == attributes[2])
								{
									foreach (XElement element3 in element2.Elements())
									{
										if (XmlUtils.GetAttributeValue<string>(element3, "Name") == attributes[3])
										{
											foreach (XElement element4 in element3.Elements())
											{
												if (XmlUtils.GetAttributeValue<string>(element4, "Name") == attributes[4])
												{
													return XmlUtils.GetAttributeValue<string>(element4, "Value");
												}
											}
										}
									}
									break;
								}
							}
							break;
						}
					}
				}
			}
			catch
			{
				// 发生异常时，直接返回空字符串或错误信息
				return string.Empty;
			}
			return string.Empty;
		}

		/// <summary>
		/// 替换XElement对象的子元素
		/// </summary>
		/// <param name="newData">替换元素</param>
		/// <param name="sourceElement">源元素</param>
		/// <param name="reserveParameters">保留参数</param>
		public static void ReplaceNodes(XElement newData, XElement sourceElement, string[] reserveParameters)
		{
			var valuePairs = new Dictionary<string, XElement>();
			if (reserveParameters != null)
			{
				foreach (XElement element in sourceElement.Elements())
				{
					string attributeName = XmlUtils.GetAttributeValue<string>(element, "Name");
					foreach (string parameter in reserveParameters)
					{
						if (attributeName == parameter)
						{
							valuePairs.Add(attributeName, element);
							break;
						}
					}
				}
			}
			sourceElement.RemoveNodes();//移除源元素
			if (reserveParameters != null)
			{
				foreach (XElement element in newData.Elements())
				{
					string attributeName = XmlUtils.GetAttributeValue<string>(element, "Name");
					if (valuePairs.TryGetValue(attributeName, out XElement value))
					{
						sourceElement.Add(value);
					}
					else
					{
						sourceElement.Add(element);
					}
				}
			}
			else
			{
				foreach (XElement element in newData.Elements())
				{
					sourceElement.Add(element);
				}
			}
		}
		public static void ReplaceNodesRecursive(XElement target, XElement source, string[] reserveParameters = null)
		{
			var valuePairs = new Dictionary<string, XElement>();
			if (reserveParameters != null)
			{
				foreach (XElement element in target.Elements())
				{
					string attributeName = XmlUtils.GetAttributeValue<string>(element, "Name");
					foreach (string parameter in reserveParameters)
					{
						if (attributeName == parameter)
						{
							valuePairs.Add(attributeName, element);
							break;
						}
					}
				}
			}
			target.RemoveNodes();
			foreach (XElement srcChild in source.Elements())
			{
				string attributeName = XmlUtils.GetAttributeValue<string>(srcChild, "Name");
				if (valuePairs.TryGetValue(attributeName, out XElement reserved))
				{
					target.Add(reserved);
				}
				else
				{
					XElement tgtChild = new(srcChild.Name, srcChild.Attributes());
					// 递归处理子节点
					if (srcChild.HasElements)
					{
						ReplaceNodesRecursive(tgtChild, srcChild, null);
					}
					else
					{
						tgtChild.Value = srcChild.Value;
					}
					target.Add(tgtChild);
				}
			}
		}
		/// <summary>
		/// 完全替换XML节点内容（包括所有子节点）
		/// </summary>
		public static void ReplaceNodesComplete(XElement sourceElement, XElement targetElement)
		{
			// 1. 完全移除目标节点的所有内容 
			targetElement.RemoveAll();

			// 2. 复制所有属性和节点 
			foreach (var attr in sourceElement.Attributes())
			{
				targetElement.SetAttributeValue(attr.Name, attr.Value);
			}

			// 3. 深度复制所有子节点
			foreach (var child in sourceElement.Elements())
			{
				targetElement.Add(new XElement(child));
			}

			//Log.Warning($"ReplaceNodesComplete({XmlUtils.GetAttributeValue<string>(sourceElement, "Name")}, {XmlUtils.GetAttributeValue<string>(targetElement, "Name")})");
		}
		/// <summary>
		/// 添加XML元素到目标节点
		/// </summary>
		public static void AddElement(XElement parentElement, string elementName, XElement sourceElement, bool overwriteIfExists = false)
		{
			if (parentElement == null || sourceElement == null)
				return;
			// 查找是否已存在同名元素
			XElement existingElement = parentElement.Elements()
				.FirstOrDefault(e => XmlUtils.GetAttributeValue<string>(e, "Name") == elementName);

			if (existingElement == null)
			{// 不存在，直接添加
				XElement newElement = new(sourceElement);
				parentElement.Add(newElement);
				//Log.Warning($"已添加缺失的 {elementName} 节点到目标存档");
			}
			else if (overwriteIfExists)
			{
				// 存在且需要覆盖，使用完全替换
				ReplaceNodesComplete(sourceElement, existingElement);
				//Log.Warning($"已覆盖已存在的 {elementName} 节点");
			}
		}
		/// <summary>
		/// 同步存档GameInfo
		/// </summary>
		public static void SynchronizeGameInfo(XElement rxElement, XElement subXElement, string path, string wpath, bool newWorld)
		{
			try
			{
				XElement gameInfoElement = null;
				if (newWorld)
				{
					if (IsChildWorld(path))
						path = Storage.GetDirectoryName(path);
					using Stream stream = Storage.OpenFile(Storage.CombinePaths(path, "Project.xml"), OpenFileMode.Read);
					rxElement = XmlUtils.LoadXmlFromStream(stream, null, throwOnError: true);
				}
				foreach (XElement element in rxElement.Element("Subsystems").Elements())
				{
					if (XmlUtils.GetAttributeValue<string>(element, "Name") == "GameInfo")
					{
						gameInfoElement = element;
						break;
					}
				}
				//foreach (XElement element in subXElement.Element("Subsystems").Elements())
				//{
				//	if (XmlUtils.GetAttributeValue<string>(element, "Name") == "GameInfo")
				//	{
				//		string[] parameters = {
				//		"WorldName","OriginalSerializationVersion",
				//		"EnvironmentBehaviorMode", "TimeOfDayMode", "AreWeatherEffectsEnabled",
				//		"TerrainGenerationMode", "IslandSize", "TerrainLevel",
				//		"ShoreRoughness", "TerrainBlockIndex", "TerrainOceanBlockIndex",
				//		"TemperatureOffset", "HumidityOffset", "SeaLevelOffset",
				//		"BiomeSize", "StartingPositionMode", "BlockTextureName",
				//		"Palette", "WorldSeed",
				//	};
				//		//if (newWorld) parameters = null;
				//		//if (newWorld)
				//		//{
				//		//    XElement timeXElement = new XElement("Value");
				//		//    XmlUtils.SetAttributeValue(timeXElement, "Name", "TotalElapsedGameTime");
				//		//    XmlUtils.SetAttributeValue(timeXElement, "Type", "double");
				//		//    XmlUtils.SetAttributeValue(timeXElement, "Value", "0");
				//		//    element.Add(timeXElement);
				//		//}
				//		//ReplaceNodes(gameInfoElement, element, parameters);
				//		break;
				//	}
				//}
				using Stream stream2 = Storage.OpenFile(Storage.CombinePaths(wpath, "Project.xml"), OpenFileMode.Create);
				XmlUtils.SaveXmlToStream(subXElement, stream2, null, throwOnError: true);
			}
			catch (Exception e)
			{
				Log.Warning("SubsystemWorld.SynchronizeGameInfo:" + e.Message);
			}
		}

		/// <summary>
		/// 安全保存路径到目标世界存档（自动创建缺失节点）
		/// </summary>
		public static void SetAttributeToTargetWorld(string path, object value, string attributeName, string type = "string")
		{
			try
			{
				XElement projectXml;
				using (var stream = Storage.OpenFile(Storage.CombinePaths(path, "Project.xml"), OpenFileMode.Read))
				{
					projectXml = XmlUtils.LoadXmlFromStream(stream, null, throwOnError: true);
				}

				var subWorldNode = GetXmlNode(projectXml, "Subsystems", ("Name", "Tartareosity"));

				if (subWorldNode == null)
				{
					subWorldNode = new XElement("Values");
					XmlUtils.SetAttributeValue(subWorldNode, "Name", "Tartareosity");
					projectXml.Element("Subsystems").Add(subWorldNode);
				}

				var targetAttribute = subWorldNode.Elements("Value")
					.FirstOrDefault(e => XmlUtils.GetAttributeValue<string>(e, "Name") == attributeName);

				if (targetAttribute == null)
				{
					targetAttribute = new XElement("Value");
					XmlUtils.SetAttributeValue(targetAttribute, "Name", attributeName);
					XmlUtils.SetAttributeValue(targetAttribute, "Type", type);
					subWorldNode.Add(targetAttribute);
				}

				XmlUtils.SetAttributeValue(targetAttribute, "Value", value);

				using (var stream = Storage.OpenFile(Storage.CombinePaths(path, "Project.xml"), OpenFileMode.Create))
				{
					XmlUtils.SaveXmlToStream(projectXml, stream, null, throwOnError: true);
				}
			}
			catch (Exception e)
			{
				Log.Error(e);
				throw; // 保留原始堆栈信息 
			}
		}

		/// <summary>
		/// 获取世界类型
		/// </summary>
		/// <param name="pathOrName">路径或者名称</param>
		/// <returns>默认返回Default</returns>
		public static WorldType GetWorldType(string pathOrName)
		{
			var worldType = WorldType.Default;
			pathOrName = pathOrName.Replace("\\", "/");
			var worldPaths = pathOrName.Split(['/']);
			var worldName = worldPaths[worldPaths.Length - 1];
			foreach (WorldType type in Enum.GetValues<WorldType>())
			{
				if (type.ToString() == worldName)
				{
					worldType = type;
					break;
				}
			}
			return worldType;
		}
		#endregion

		/// <summary>
		/// 创建完整传送门
		/// </summary>
		public void GenerateDoor(Point3 position)
		{
			//int cid = GetPortalBlock(WorldType);
			//for (int x = 0; x < 4; x++)
			//{
			//	for (int y = 0; y < 5; y++)
			//	{
			//		int id = 0;
			//		if (x == 0 || x == 3)
			//			id = cid;
			//		if ((x == 1 || x == 2) && (y == 0 || y == 4))
			//			id = cid;
			//		m_subsystemTerrain.ChangeCell(position.X + x, position.Y + y, position.Z, id);
			//	}
			//}
			//var transferBlockBehavior = base.Project.FindSubsystem<SubsystemAltarBlockBehavior>(true);
			//transferBlockBehavior.CreateEntrance(position + new Point3(1, 0, 0), position + new Point3(2, 0, 0), true, WorldType);
		}

	}
}
